import os, time

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper 
from django.utils.encoding import smart_unicode, smart_str
from django.views.decorators.csrf import csrf_exempt

var_path = '/Users/liushuai/git/DjangoProject/FileBrowser/uploads/'
f_name_list = os.listdir(var_path)

def index(request):
	updateFileList()
	return render_to_response('index.html', {'f_name_list':f_name_list}, RequestContext(request))

def download(request, file_index):
	f_name = smart_str(f_name_list[int(file_index) - 1])
	full_path = ''.join((var_path, f_name))
	wrapper = FileWrapper(file(full_path))
	response = HttpResponse(wrapper, mimetype='application/octet-stream')
	response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(f_name)
	response['Content-Length'] = os.path.getsize(full_path)  
	return response

@csrf_exempt
def upload(request):
	if request.method == 'POST':
		f = request.FILES['fileData']
		f_name = getFileNameByCurrentTime(f.name)
		destination = open('uploads/' + f_name, 'w')
		for chunk in f.chunks():
			destination.write(chunk)
		destination.close()
		updateFileList()
	return HttpResponse(status=200)


def getFileNameByCurrentTime(oldName):
	'''get the new file name by current time. if the new name already exists, return the name with a suffix'''
	global var_path
	format = '%Y%m%d%H%M%S'
	suffix = '_1'
	newName_prefix = time.strftime(format,time.localtime(time.time()))
	newName_suffix = oldName.split('.')[-1:][0]
	newName =  newName_prefix + '.' + newName_suffix
	if os.path.exists(var_path + newName):
		newName = newName_prefix + suffix + '.' + newName_suffix
	return newName


def updateFileList():
	global f_name_list, var_path
	f_name_list = os.listdir(var_path)